# Copyright (C) 2006  Apptility LLC  http://www.apptility.com
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

require 'app/apis/integration/sugarcrm/ajuby_sugarcrm_api.rb'
require 'basecamp'
class IntegrationController < ApplicationController
  
  def edit
    @node_name = params['node']
    return MashupNode.new if @node_name.nil?
    @mashup_node = find_mashup_node(@node_name)
    @mashup_node
  end
    
  def save
    @node_name = params['mashup_node']['name']
    #AjubyLogger.logInfo("@node_name>>> : #{@node_name}")
    if !(@mashup_node = find_mashup_node(@node_name)).nil?
        if update_mashup(@mashup_node, @params)
          flash[:simplemsg] = 'Mashup was successfully updated for : '<< @node_name
        else
          render :action =>'edit'
        end
    end
    @mashup_node   
  end    
  
  def test_connection
    
    @test_connection = nil

    if params['node']=='salesforce'
      
       if params['op']!=nil
        @test_connection = AjubySalesforceApi.new(session).test_connection
        #AjubyLogger.logInfo("@test_connection><>>>>>: #{@test_connection}")
      end
    
      if AjubySalesforcePipe.is_connection_failed(@test_connection)
        flash[:message] = "Test connection failed because : " <<@test_connection.connection_message
        render :action =>'adapter_error'
      else
        @mashup_node = find_mashup_node(params['node'])
        @test_connection 
        @mashup_node
        render :action =>'save'
      end
    end
    
    if params['node'] == 'sugarcrm'
      if params['op']!=nil
        
        @test_connection = AjubySugarcrmApi.new(session).test_connection
        AjubyLogger.logInfo("@test_connection><>>>>>: #{@test_connection}")
      end
    
      if AjubySugarcrmPipe.is_connection_failed(@test_connection)
        flash[:message] = "Test connection failed because : " <<@test_connection.connection_message
        render :action =>'adapter_error'
      else
        @mashup_node = find_mashup_node(params['node'])
        @test_connection 
        @mashup_node
        render :action =>'save'
      end
    end
  end

  
  def browse_objects
  
    if params['node']=='salesforce'
      begin
        @modules_list = AjubySalesforceApi.new(session).get_modules
      rescue Exception => e
        flash[:message] = "Browse objects failed" 
        @detailed_msg = AjubySalesforcePipe.build_err_trace("browse_objects failed" << e.message)
        render :action =>'adapter_error'
      end  
    end 
       
    if params['node']=='sugarcrm'
      begin
        @modules_list = AjubySugarcrmApi.new(session).get_modules
      rescue Exception => e
        flash[:message] = "Browse objects failed" 
        @detailed_msg = AjubySugarcrmPipe.build_err_trace("browse_objects failed" << e.message)
        render :action =>'adapter_error'
      end  
    end
     
  end  

  def objectdetail
    
    if params['node']=='salesforce'
      begin
        @records = AjubySalesforceApi.new(session).get_module_records(params['name'])
      rescue Exception => e
        flash[:message] = "Object detail failed" 
        @detailed_msg = AjubySalesforcePipe.build_err_trace("objectdetail failed" << e.message)
        render :action =>'adapter_error'
      end  
    end 
      
    if params['node']=='sugarcrm'
      begin
        @records = AjubySugarcrmApi.new(session).get_module_records(params['name'])
      
        if (@records['result_count'] > 0)
          @records
        else
          flash[:message] = "Object detail failed"
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("object detail failed" << " - 'No #{params['name']} found' ")  
          render :action =>'adapter_error'
        end
      rescue Exception => e
        flash[:message] = "Object detail failed" 
        @detailed_msg = AjubySugarcrmPipe.build_err_trace("object detail failed" << e.message)
        render :action =>'adapter_error'
      end  
    end 
  end  
  
  def userdetail
  
    if params['node']=='sugarcrm'
      begin
        @records = AjubySugarcrmApi.new(session).get_user_records(params['name'],params['record'])
      
        if (@records['result_count'] > 0)
          @records
        else
          flash[:message] = "Object detail failed"
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("User detail failed" << " - 'No #{params['name']} found' ")  
          render :action =>'adapter_error'
        end
      rescue Exception => e
        flash[:message] = "User detail failed" 
        @detailed_msg = AjubySugarcrmPipe.build_err_trace("object detail failed" << e.message)
        render :action =>'adapter_error'
      end  
   end 
  end
  
  def newrecord
    
    if params['node']=='sugarcrm'
      begin
        if (params['name'] == 'Contacts' || params['name'] == 'Opportunities' || params['name'] == 'Leads' || params['name'] == 'Accounts' || params['name'] == 'Cases')
          name11 = params['name']
        else
          flash[:message] = "Record creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Record creation failed"  << " - Your WSDL file is not providing the facility to create #{params['name']}")
          render :action =>'adapter_error'
        end
      rescue Exception => e
        flash[:message] = "Record creation failed" 
        @detailed_msg = AjubySugarcrmPipe.build_err_trace("Record creation failed"  << e.message)
        render :action =>'adapter_error'
      end  
   end 
  
  end
  
   def saverecord
    if(params[:module_name]=='Contacts')
      begin
      
        @module_name = params[:module_name]
        @first_name = params[:first_name]
        @last_name  = params[:last_name]
        @email_address = params[:email_address] 
        
        @responce = AjubySugarcrmApi.new(session).create_new_contact(params[:first_name],params[:last_name],params[:email_address])
        
        if(@responce!=0)
          flash[:simplemsg] = "A Contact has been successfully created."
        else
          flash[:message] = "Contact creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Contact creation failed"  << " - We encountered an internal error. Please try again.")
          render :action =>'adapter_error' 
        end
      rescue Exception => e
          flash[:message] = "Contact creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Contact creation failed"  << e.message)
          render :action =>'adapter_error' 
      end
    elsif(params[:module_name]=='Accounts')
      begin
        
        @module_name = params[:module_name]
        @account_name = params[:account_name]
        @phone_number = params[:phone_number]
        @website = params[:website]
      
        @responce = AjubySugarcrmApi.new(session).create_new_account(params[:account_name],params[:phone_number],params[:website])
        
        if(@responce!=0)
          flash[:simplemsg] = "An Account has been successfully created."
        else
          flash[:message] = "Account creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Account creation failed"  << " - We encountered an internal error. Please try again.")
          render :action =>'adapter_error' 
        end
      rescue Exception => e
          flash[:message] = "Account creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Account creation failed"  << e.message)
          render :action =>'adapter_error' 
      end
    elsif(params[:module_name]=='Leads')
      begin
        
        @module_name = params[:module_name]
        @first_name = params[:first_name]
        @last_name  = params[:last_name]
        @email_address = params[:email_address] 
        
        @responce = AjubySugarcrmApi.new(session).create_new_lead(params[:first_name],params[:last_name],params[:email_address])
        
        if(@responce!=0)
          flash[:simplemsg] = "A Lead has been successfully created."
        else
          flash[:message] = "Lead creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Lead creation failed"  << " - We encountered an internal error. Please try again.")
          render :action =>'adapter_error' 
        end
      rescue Exception => e
          flash[:message] = "Lead creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Lead creation failed"  << e.message)
          render :action =>'adapter_error' 
      end
    elsif(params[:module_name]=='Cases')
      begin
        
        @module_name = params[:module_name]
        @case_name = params[:case_name]
        
        @responce = AjubySugarcrmApi.new(session).create_new_case(params[:case_name])
        
        if(@responce!=0)
          flash[:simplemsg] = "A Case has been successfully created."
        else
          flash[:message] = "Case creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Case creation failed"  << " - We encountered an internal error. Please try again.")
          render :action =>'adapter_error' 
        end
      rescue Exception => e
          flash[:message] = "Case creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Case creation failed"  << e.message)
          render :action =>'adapter_error' 
      end
      
    elsif(params[:module_name]=='Opportunities')
      begin
      
        @module_name = params[:module_name]
        @opportunity_name = params[:opportunity_name]
        @amount = params[:amount]
      
        @responce = AjubySugarcrmApi.new(session).create_new_opportunity(params[:opportunity_name],params[:amount])
        
        if(@responce!=0)
          flash[:simplemsg] = "An Opportunity has been successfully created."
        else
          flash[:message] = "Opportunity creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Opportunity creation failed"  << " - We encountered an internal error. Please try again.")
          render :action =>'adapter_error' 
        end
      rescue Exception => e
          flash[:message] = "Opportunity creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Opportunity creation failed"  << e.message)
          render :action =>'adapter_error' 
      end
    
    elsif(params['module'] == 'Project')
      begin
      
        @module_name = params['module']
        @project_name = params['name']
             
        @responce = AjubySugarcrmApi.new(session).create_new_project(@project_name)
        
        if(@responce!=0)
          flash[:simplemsg] = "A Project has been successfully save to SugarCRM."
        else
          flash[:message] = "Project creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Project creation failed"  << " - We encountered an internal error. Please try again.")
          render :action =>'adapter_error' 
        end
      rescue Exception => e
          flash[:message] = "Project creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Project creation failed"  << e.message)
          render :action =>'adapter_error' 
      end
      
      elsif(params['module'] == 'ProjectTask')
        begin
        
          @module_name = params['module']
          @project_name = params['name']
          @task_name = AjubyTools.base64decode(params['task'])
          
          @project_id = search(@project_name)
          
          if(@project_id == 1)
            
            @responce_p = AjubySugarcrmApi.new(session).create_new_project(@project_name)
            @responce = AjubySugarcrmApi.new(session).create_new_projecttask(@task_name,@responce_p)
          else
          
            @responce = AjubySugarcrmApi.new(session).create_new_projecttask(@task_name,@project_id)
          end
          
          if(@responce!=0)
            flash[:simplemsg] = "A Project Task has been successfully save to SugarCRM."
          else
            flash[:message] = "Project creation failed" 
            @detailed_msg = AjubySugarcrmPipe.build_err_trace("Project creation failed"  << " - We encountered an internal error. Please try again.")
            render :action =>'adapter_error' 
          end
      rescue Exception => e      
          flash[:message] = "Project Task creation failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Project Task creation failed"  << e.message)
          render :action =>'adapter_error' 
      end
      
    else
      flash[:message] = "Save record failed" 
      @detailed_msg = AjubySugarcrmPipe.build_err_trace("save record failed"  << " - Your WSDL file is not providing the facility to create #{params['name']}")
      render :action =>'adapter_error'
    end
    
   end
   
   def browse_projects
   
     @values = MashupNode.find(:all, :conditions => [ "name =? AND user_id =?", "#{params['node']}", current_user.id])
            
                @values.each do |@value|
                @username = @value.username
                @password = AjubyTools.base64decode(@value.password)
                @url = @value.wsdl_url
              
                end 
   
   
     @conn = Basecamp.new(@url, @username, @password)
     
   begin
     @projects = @conn.projects
     rescue Exception => e      
          flash[:message] = "Browse Projects failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Browse Projects failed - "  << e.message)
          render :action =>'adapter_error' 
      end
   end
   
   def todolist
    
     @values = MashupNode.find(:all, :conditions => [ "name =? AND user_id =?", "#{params['node']}", current_user.id])
            
                @values.each do |@value|
                @username = @value.username
                @password = AjubyTools.base64decode(@value.password)
                @url = @value.wsdl_url
              
                end 
   
   
    @conn = Basecamp.new(@url, @username, @password)
    
    begin
      @todolists=@conn.lists(params['id'])
    rescue Exception => e      
          flash[:message] = "Browse To-Dolist failed" 
          @detailed_msg = AjubySugarcrmPipe.build_err_trace("Browse To-Dolist failed - "  << e.message)
          render :action =>'adapter_error' 
      end
   end
   
   def search(project_name)
   
    
      @records = AjubySugarcrmApi.new(session).get_module_records("Project")
     
      for @recordlist in @records.entry_list
					
					for @record in @recordlist.name_value_list
					
						if(@record.name == "name")
							@name = @record.value
							
						end
					
						if(@record.name == "id")
							@id = @record.value
							
						end
						
						if(@name == project_name)
						  return @id
						 
						end
			
					end
		end			
      
      return 1
   end    
     
    
  
  private

    # A helper method to find mashup node by name, and insert
    # appropriate error messages into the flash if it couldn't be
    # found.
    def find_mashup_node(node_name)
      #@mashup_node = MashupNode.find_by_name(node_name)
      @mashup_node = MashupNode.find(:first, :conditions => [ "name =?", node_name])
      if @mashup_node == nil
        @mashup_node = MashupNode.new 
      end  
      @mashup_node
    end
  
  def generate_blank
    #AjubyLogger.logInfo("request.method>>> #{request.method}")
    case request.method
    when :get
      render
      return true
    end
    return false
  end
  
  def update_mashup (mashup, params)
      mashup.name = params['mashup_node']['name']
      mashup.username = params['mashup_node']['username']
      mashup.user_id=current_user.id
      @pwd = params['mashup_node']['password']
      if @pwd!=nil and @pwd!=''
        mashup.password = AjubyTools.base64encode(params['mashup_node']['password'])
      end
      mashup.wsdl_url = params['mashup_node']['wsdl_url']
      mashup.debug_soap = params['mashup_node']['debug_soap']
      mashup.records_size = params['mashup_node']['records_size']
      @skey = params['mashup_node']['secret_key']
      if @skey!=nil and @skey!=''
        mashup.custom_field2 = AjubyTools.base64encode(params['mashup_node']['secret_key'])
      end
      mashup.custom_field1=params['mashup_node']['access_key']
      if mashup.save
        return true
      else
        return false
      end
         
  end  

end
 